package com.grape.juc.safe.communication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述:生产消费一个个执行
 * @author: myx
 * @date: 2019-05-08
 * Copyright © 2019-grape. All rights reserved.
 */
public class ConditionTest {
    public static void main(String[] args) {
        ConditionRes res = new ConditionRes();
        Condition newCondition = res.lock.newCondition();
        ConditionIntThradSolve ConditionIntThradSolve = new ConditionIntThradSolve(res,newCondition);
        ConditionOutThradSlove ConditionOutThradSlove = new ConditionOutThradSlove(res,newCondition);
        ConditionIntThradSolve.start();
        ConditionOutThradSlove.start();
    }
}

/**
 * 共享对象
 */
class ConditionRes {
    public String userSex;
    public String userName;
    //线程通讯标识
    public boolean flag = false;
    Lock lock = new ReentrantLock();
}

/**
 * 写线程(解决问题)
 */
class ConditionIntThradSolve extends Thread {
    private ConditionRes res;
    Condition newCondition;

    public ConditionIntThradSolve(ConditionRes res,Condition newCondition) {
        this.res = res;
        this.newCondition=newCondition;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            try {
                res.lock.lock();
                if (res.flag) {
                    newCondition.await();
                }
                if (count == 0) {
                    res.userName = "沐宇熙";
                    res.userSex = "男";
                } else {
                    res.userName = "小紅";
                    res.userSex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                // 唤醒当前线程
                newCondition.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                res.lock.unlock();
            }

        }
    }
}

/**
 * 读线程(解决问题)
 */
class ConditionOutThradSlove extends Thread {
    private ConditionRes res;
    private Condition newCondition;

    public ConditionOutThradSlove(ConditionRes res,Condition newCondition) {
        this.res = res;
        this.newCondition=newCondition;
    }

    @Override
    public void run() {
        while (true) {
            try {
                res.lock.lock();
                if (!res.flag) {
                    newCondition.await();
                }
                System.out.println(res.userName + "," + res.userSex);
                res.flag = false;
                newCondition.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                res.lock.unlock();
            }
        }
    }
}



